package ch.netcetera.planningpoker.client.ui.admin.moderate;

import java.util.logging.Level;
import java.util.logging.Logger;

import ch.netcetera.planningpoker.client.model.GameProxy;
import ch.netcetera.planningpoker.client.ui.admin.round.ModeratorRoundPresenter;
import ch.netcetera.planningpoker.client.ui.events.RoundStatusChangedEvent;
import ch.netcetera.planningpoker.client.ui.events.UserListChangedEvent;
import ch.netcetera.planningpoker.client.ui.main.MainPagePresenter;
import ch.netcetera.planningpoker.client.ui.participant.create.CreateParticipantPresenter;
import ch.netcetera.planningpoker.client.ui.widget.userlist.UserListPresenter;
import ch.netcetera.planningpoker.shared.GameRequestFactory;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ParameterTokenFormatter;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;

public class ModerationPresenter extends
        Presenter<ModerationPresenter.IView, ModerationPresenter.IProxy> {

    private static final Logger logger = Logger
            .getLogger(ModerationPresenter.class.getName());

    public static final String NAME_TOKEN = "moderate";
    public static final String ARG_GAME_ID = "gameId";

    @ProxyCodeSplit
    @NameToken("moderate")
    public interface IProxy extends ProxyPlace<ModerationPresenter> {

    }

    public interface IView extends View {

        HasText getGameTitle();
        
        void setAdminUrl(String url);
        
        void setPublicUrl(String url);
        
        HasWidgets getUserListContainer();
        
        HasWidgets getCurrentRound();

    }

    private GameRequestFactory requestFactory;

    private UserListPresenter userListPresenter;

    private ModeratorRoundPresenter roundPresenter;

    @Inject
    public ModerationPresenter(EventBus eventBus,
            PlaceManager placeManager, IView view, IProxy proxy,
            GameRequestFactory requestFactory, UserListPresenter userListPresenter, ModeratorRoundPresenter roundPresenter) {
        super(true, eventBus, view, proxy);
        this.requestFactory = requestFactory;
        this.userListPresenter = userListPresenter;
        this.roundPresenter = roundPresenter;
    }

    @Override
    protected void onBind() {
        getView().getUserListContainer().add(userListPresenter.getWidget());
        getView().getCurrentRound().add(roundPresenter.getWidget());
    }

    @Override
    protected void revealInParent() {
        RevealContentEvent.fire(this, MainPagePresenter.MainContentSlot, this);
    }

    @Override
    public void prepareFromRequest(PlaceRequest request) {
        super.prepareFromRequest(request);
        String gameIdString = request.getParameter(ARG_GAME_ID, "");
        logger.info("Landed on moderation argument gameId : " + gameIdString);

        Long gameId = null;
        try {
            gameId = Long.valueOf(request.getParameter("gameId", "0"));
        } catch (NumberFormatException e) {
            logger.log(Level.SEVERE, "parsing parameter failed", e);
        }

        if (gameId != null) {
            requestFactory.getGameRequest().findGame(gameId)
                    .fire(new Receiver<GameProxy>() {

                        @Override
                        public void onSuccess(GameProxy game) {
                            displayGame(game);
                        }
                    });
        }
        if (gameId != null) {
            getEventBus().fireEventFromSource(new UserListChangedEvent(gameId), this);
            getEventBus().fireEventFromSource(new RoundStatusChangedEvent(gameId), this);
        }

    }
    
    public void displayGame(GameProxy game) {
        ParameterTokenFormatter formatter = new ParameterTokenFormatter();
        getView().getGameTitle().setText(game.getTitle());
        String baseUrl = Window.Location.getHref().replace(Window.Location.getHash(), "");
        PlaceRequest adminRequest = new PlaceRequest(ModerationPresenter.NAME_TOKEN).with(ModerationPresenter.ARG_GAME_ID, String.valueOf(game.getId()));
        getView().setAdminUrl(baseUrl + "#" + formatter.toPlaceToken(adminRequest));
        PlaceRequest publicRequest = new PlaceRequest(CreateParticipantPresenter.NAME_TOKEN).with(CreateParticipantPresenter.ARG_GAME_ID, String.valueOf(game.getId()));
        getView().setPublicUrl(baseUrl + "#" + formatter.toPlaceToken(publicRequest));
        
    }
}
